/*
 * @Author: toString
 * @Date: 2024-07-26 14:00:51
 * @LastEditTime: 2024-07-30 17:13:54
 * @LastEditors: toString
 * @Description: etherjs帮助类
 * @FilePath: /token-for-token-front/src/utils/utils.js
 */

import { ethers } from "ethers";
import { showNotify } from "vant";
import i18n from "@/language/index.js"; // 导入 i18n 模块，国际化
const { t } = i18n.global;

const abi = [
  "function transfer(address recipient, uint256 amount ) external returns (bool)",
  "function allowance(address owner, address spender) external view returns (uint256)",
  "function approve(address spender, uint256 amount) external returns (bool)",
  "function decimals() external pure returns (uint8)",
  "function balanceOf(address) external view returns (uint256)",
  "function totalSupply() external view returns (uint256)",
];

let address = "";
// 获取当前语言环境对应的提示消息
// const installMetaMaskMessage = t('global.installMetaMask');
// 连接钱包
export const connectWallet = async (chainId) => {
  try {
    const { ethereum } = window;
    if (!ethereum) {
      showNotify({
        message: t("global.InstallMetaMask"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }
    try {
      await ethereum.request({
        method: "wallet_switchEthereumChain",
        params: [{ chainId: "0x" + chainId.toString(16) }],
      });
    } catch (error) {
      console.log(error);
    }

    const accounts = await ethereum.request({ method: "eth_requestAccounts" });
    console.log("Connected", accounts[0]);
    address = ethers.utils.getAddress(accounts[0]);
    return address;
  } catch (error) {
    console.log(error);
  }
};

// 获取公链余额
export const getBalance = async (address) => {
  try {
    const { ethereum } = window;
    if (!ethereum) {
      showNotify({
        message: t("global.InstallMetaMask"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }
    const provider = new ethers.providers.Web3Provider(ethereum);
    const balance = await provider.getBalance(address);
    return ethers.formatEther(balance);
  } catch (error) {}
};

// 获取合约
export const getContract = async (token) => {
  try {
    const { ethereum } = window;
    if (!ethereum) {
      showNotify({
        message: t("global.InstallMetaMask"),
        color: "#ffffff",
        background: "#f56c6c",
      });
      return;
    }
    // let provider, signer, contract;
    // if (rpc) {
    //   provider = new ethers.providers.JsonRpcProvider(rpc);
    // } else {
    //   provider = new ethers.providers.Web3Provider(window.ethereum);
    // }
    // if (isSend && rpc) {
    //   provider = await provider.getSigner();
    // }
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(token, abi, signer);
    return contract;
  } catch (error) {
    console.log(error);
  }
};

// 代币转账
export const transfer = async (token, to, amount) => {
  try {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(token, abi, signer);
    const decimals = await contract.decimals();
    // const allowance = await contract.allowance(address, to);
    let amount1 = ethers.utils.parseUnits(amount.toString(), decimals);
    // if (allowance < amount) {
    //   await contract.approve(to, amount);
    // }
    const tx = await contract.transfer(to, amount1);
    return tx.hash;
  } catch (error) {
    console.log(error);
  }
};

// 授权
export const approve = async (token, spender, amount, rpc = "") => {
  try {
    const contract = await getContract(token);
    const tx = await contract.approve(spender, amount);
    return tx;
  } catch (error) {
    console.log(error);
  }
};

// 获取授权额度
export const allowance = async (token, owner, spender, rpc = "") => {
  try {
    const contract = await getContract(token);
    const allowance = await contract.allowance(owner, spender);
    return allowance;
  } catch (error) {
    console.log(error);
  }
};

// 获取代币余额
export const balanceOf = async (token, address) => {
  try {
    const contract = await getContract(token);
    let balance = await contract.balanceOf(address);
    const decimals = await contract.decimals();
    balance = ethers.utils.formatEther(balance, decimals);
    return balance;
  } catch (error) {
    console.log(error);
  }
};

export default {
  connectWallet,
  getBalance,
  getContract,
  transfer,
  approve,
  allowance,
  balanceOf,
};
